// 导入 http 模块
import http from 'wechat-http'
//设置基地址
http.baseURL = 'https://live-api.itheima.net'

//设置请求拦截器
http.intercept.request = function (options) {
  const { token } = getApp()
  console.log(options)
  if (!options.header) {
    options.header = {
      Authorization: `Bearer ${token}`
    }
  }

  return options
}

//设置相应拦截器
http.intercept.response = async function ({ data, config }) {
  if (data.code === 401) {
    const app = getApp()

    if (config.url.includes('/refreshToken')) {
      const currentPage = getCurrentPages().pop().route
      // 跳由跳转（登录页面）
      return wx.redirectTo({
        url: '/pages/login/index?redirectURL=' + currentPage
      })
    }

    const {
      code,
      data: { token, refreshToken }
    } = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: `Bearer ${app.refreshToken}`
      }
    })
    if (code !== 10000) return wx.utils.toast()

    app.setToken('token', token)
    app.setToken('refreshToken', refreshToken)

    config = Object.assign(config, {
      header: {
        //更新后的token
        Authorization: 'Bearer ' + token
      }
    })
    console.log(config)
    // 重新发请求
    return http(config)
  }
  return data
}

//挂载到全局
wx.http = http

export default http
